﻿using System;
using System.Linq;
using System.Reflection;

namespace XamlDom.Runtime
{
    public class XamlTypeFinder
    {
        /// <summary>
        /// 根据xmlNameSpace找到相应的ClrNameSpace
        /// 再根据相应的名称反射出相应的类型
        /// </summary>
        /// <param name="xmlNameSpace"></param>
        /// <param name="localName"></param>
        /// <returns></returns>
        public static Type GetType(string xmlNameSpace, string localName)
        {
            foreach (AssemblyInfo assemblyInfo in AssemblyLoader.assemblyInfos)
            {
                Assembly runtimeAssembly = assemblyInfo.RuntimeAssembly;
                XamlNamespace xamlNameSpace = assemblyInfo.XamlNameSpaces.Where(x => x.XmlNamespace.Equals(xmlNameSpace)).FirstOrDefault();
                if (xamlNameSpace != null)
                {
                    foreach (string clrNameSpace in xamlNameSpace.ClrNamespaces)
                    {
                        Type type = runtimeAssembly.GetType(clrNameSpace + "." + localName);
                        if (type != null)
                        {
                            return type;
                        }
                    }
                }
            }
            return null;
        }
    }
}
